// md5.worker.js
// 另一种处理方案：https://juejin.cn/post/7434460220845539367
// importScripts('https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.2/spark-md5.min.js');
importScripts('/node_modules/spark-md5/spark-md5.min.js');

onmessage = function (e) {
    const {file, size} = e.data;
    const total = Math.ceil(file.size / size);
    let index = 0;

    const spark = new self.SparkMD5.ArrayBuffer();
    const reader = new FileReader();

    // 计算md5
    reader.onload = (e) => {
        spark.append(e.target.result);
        index ++;
        if (index < total) {
            read();
        } else {
            const md5 = spark.end();
            spark.destroy(); // 清理内存
            self.postMessage({
                status: 'computed',
                value: md5,
                total: total
            });
        }
    };


    //分块读取文件
    const read = () => {
        const start = index * size ;
        const end = Math.min(start + size, file.size);
        reader.readAsArrayBuffer(file.slice(start, end));
        self.postMessage({
            status: 'computing',
            percent: Math.round((index + 1) / total * 100),
        });
    };

    read(); // 开始处理
};